<?php
/**
 * Created by PhpStorm.
 * User: YongXuan.Huang
 * Date: 2017/9/9
 * Time: 12:37
 */


/**
 * 递归创建
 * @param $dir
 * @return bool
 */
function makeDirectory($dir)
{
    return is_dir($dir) or makeDirectory(dirname($dir)) and mkdir($dir, 0777);
}

/**
 * 删除文件夹 包括里面的子文件和目录
 * @param $path
 */
function removeDirectory($path)
{
    $files = scandir($path);
    foreach ($files as $key => $value) {
        if ($value === '.' || $value === '..') {
            continue;
        }
        $file = $path . DIRECTORY_SEPARATOR . $value;
        if (is_file($file)) {
            unlink($file);
            continue;
        }
        if (is_dir($file)) {
            removeDirectory($file);
        }
    }
    rmdir($path);
}

function isImage($file)
{
    $types = ['image/jpeg', 'image/png', 'image/gif'];
    return in_array($file['type'], $types);
}


function uploadFileSave($file, $path = '/files/'){
    if ($file == null || !isImage($file)) {
        return null;
    }
    $root = __DIR__ . '/../../public';
    $fileName = md5_file($file['tmp_name']) . '.' . str_replace('image/', '', $file['type']);
    $path = $path . date('Ymd', time());
    $dirName = $root . $path;
    if (!is_dir($dirName)) {
        makeDirectory($dirName);
    }
    $filePath = $dirName . DIRECTORY_SEPARATOR . $fileName;
    move_uploaded_file($file['tmp_name'], $filePath);
    return $path . '/' . $fileName;
}